package com.common.client;

import java.util.ArrayList;
import java.util.LinkedHashMap;

import com.common.shared.model.Classifier;
import com.google.gwt.core.client.JavaScriptObject;
import com.smartgwt.client.widgets.form.fields.FormItemIcon;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.FormItemClickHandler;
import com.smartgwt.client.widgets.form.fields.events.FormItemIconClickEvent;

public abstract class ClassifComboBox extends SelectItem {

	protected int type;
	protected LinkedHashMap<String, String> valueMap;
	protected boolean withId;

	public ClassifComboBox() {
		super();
	}

	public ClassifComboBox(JavaScriptObject jsObj) {
		super(jsObj);
	}

	public ClassifComboBox(String name, String title) {
		super(name, title);
	}

	public ClassifComboBox(String name) {
		super(name);
	}

	public void setData(Classifier[] classifiers, int type, boolean editable,
			boolean withId) {
		this.withId = withId;
		// setCompleteOnTab(true);
		this.type = type;
		if (classifiers == null)
			classifiers = new Classifier[] {};
		if (editable) {
			FormItemIcon piAdd = new FormItemIcon();
			piAdd.addFormItemClickHandler(new FormItemClickHandler() {

				@Override
				public void onFormItemClick(FormItemIconClickEvent event) {
					addClassifier();
				}
			});
			this.setIcons(piAdd);
		}
		valueMap = new LinkedHashMap<String, String>();
		for (int i = 0; i < classifiers.length; i++) {
			Classifier cl = classifiers[i];
			String value = cl.getTypename();
			if (withId)
				value = cl.getTypeid() + "." + value;
			valueMap.put(new Integer(cl.getTypeid()).toString(), value);

		}
		this.setValueMap(valueMap);
	}

	public void setData(ArrayList<Classifier> classifiers, int type,
			boolean editable, boolean withId) {
		if (classifiers == null) {
			classifiers = new ArrayList<Classifier>();
		}
		setData(classifiers.toArray(new Classifier[] {}), type, editable,
				withId);
	}

	protected abstract void addClassifier();
}
